﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace WindowsFormsApplication1
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();

			//开启线程
			//Thread thread = new Thread(new ThreadStart(SocketListen));

			Thread thread = new Thread(new ThreadStart(Listen));
			thread.Start();
			txtInfo.AppendText("正在监听\r\n");
		}
		protected delegate void UpdateDisplayDelegate(string text);

		public void Listen()
		{
			try
			{
				IPAddress ipAdress = IPAddress.Any;
				TcpListener tcpListener = new TcpListener(ipAdress, 9999);
				while (true)
				{
					tcpListener.Start();
					TcpClient tcpClient = tcpListener.AcceptTcpClient();
					NetworkStream ns = tcpClient.GetStream();
					StreamReader sr = new StreamReader(ns);
					string result = sr.ReadToEnd();
					Invoke(new UpdateDisplayDelegate(UpdateDisplay), new object[] { result });
					tcpClient.Close();
					tcpListener.Stop();
				}
			}
				
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
			
		}

		public void SocketListen()
		{
			Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			listener.Bind(new IPEndPoint(IPAddress.Any, 9999));
			listener.Listen(0);
			while (true)
			{
				Socket socket = listener.Accept();
				Stream netStream = new NetworkStream(socket);
				StreamReader reader = new StreamReader(netStream);
				string result = reader.ReadToEnd();
				Invoke(new UpdateDisplayDelegate(UpdateDisplay), new object[] { result });
				socket.Close();
			}
			
			listener.Close();
		}

		public void UpdateDisplay(string text)
		{
			txtInfo.AppendText(text + "\r\n");
		}

		private void Form1_FormClosing(object sender, FormClosingEventArgs e)
		{
		}

		private void Form1_FormClosed(object sender, FormClosedEventArgs e)
		{
			
		}

	}
}
